<template>

    <a-modal v-model:visible="visible" :unmount-on-close="true" title="创建用户" draggable @cancel="handleCancel"
             @before-ok="handleOk" :width="500">
        <a-form ref="formRef" :model="form">
            <a-form-item field="name" label="用户名" :rules="[{required:true,message:'请输入用户名'}]">
                <a-input v-model="form.name" placeholder="请输入用户名"/>
            </a-form-item>

            <a-form-item field="password" label="用户密码" :rules="[{required:true,message:'请输入用户密码'}]">
                <a-input-password v-model="form.password" placeholder="请输入用户密码"/>
            </a-form-item>

            <a-form-item field="password2" label="确认密码" :rules="[{required:true,message:'请再次输入密码'}]">
                <a-input-password v-model="form.password2" placeholder="请再次输入密码"/>
            </a-form-item>

            <a-form-item field="sysinfo" label="系统信息"
                         :rules="[{required:true,message:'请选择是否允许查看系统信息'}]">
                <a-select v-model="form.sysinfo">
                    <a-option value="1">允许查看</a-option>
                    <a-option value="0">禁止查看</a-option>
                </a-select>
            </a-form-item>

        </a-form>
    </a-modal>


</template>

<script setup lang="ts">

import {reactive, ref} from "vue";
import {doQuery} from "../../../scripts/mapper";
import {QueryResult} from "../../../scripts/type";
import {Message} from "@arco-design/web-vue";

const visible = ref(false);
const formRef = ref();

const emits = defineEmits(['done'])

let form = reactive({
    name: undefined,
    password: undefined,
    password2: undefined,
    sysinfo: "1"
})

const add = () => {
    form = reactive({
        name: undefined,
        password: undefined,
        password2: undefined,
        sysinfo: "1"
    })
    visible.value = true
}

const handleCancel = () => {
    visible.value = false
}

const handleOk = (done) => {
    formRef.value.validate((errors) => {
        if (!errors) {
            if (form.password !== form.password2) {
                Message.error("两次密码输入不一致");
                done(false)
                return
            }
            let sql = `CREATE USER ${form.name} PASS '${form.password}' sysinfo ${form.sysinfo};`
            doQuery(sql).then((result: QueryResult) => {
                if (result.success && result.data) {
                    Message.success("用户创建成功");
                    emits('done')
                    done()
                } else {
                    Message.error("用户创建失败" + (result.message ? (": " + result.message) : ""))
                    done(false)
                }
            })
        } else {
            done(false)
        }
    })
}

defineExpose({
    add
})


</script>

<style scoped>

</style>
